package com.ouyy.volunteerservice.volunteer.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ouyy.volunteerservice.volunteer.domain.po.Organizations;
import com.ouyy.volunteerservice.volunteer.domain.po.Volunteer;
import com.ouyy.volunteerservice.volunteer.mapper.OrganizationsMapper;
import com.ouyy.volunteerservice.volunteer.service.OrganizationsService;
import com.ouyy.volunteerservice.volunteer.service.VolunteerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/organizations")
public class OrganizationsController {

    @Autowired
    private OrganizationsService organizationsService;

    @Autowired
    private VolunteerService volunteerService;


    @Autowired
    private OrganizationsMapper organizationsMapper;
    /**
     * 组织登录
     */
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        Organizations org = organizationsService.findByOrganAndPassword(username, password);
        return org != null ? "登录成功" : "用户名或密码错误";
    }

    /**
     * 组织注册
     */
    @PostMapping("/register")
    public String register(@RequestBody Organizations organization) {
        String organizationName = organization.getOrganizationName();
        if (organizationName != null && !organizationName.isEmpty()) {
            Organizations existingOrg = organizationsService.getOne(new QueryWrapper<Organizations>().eq("organization_name", organizationName));
            if (existingOrg != null) {
                return "组织名已存在";
            }
        }
        boolean saved = organizationsService.save(organization);
        return saved ? "注册成功" : "注册失败";
    }

    /**
     * 查询所有组织
     */
    @GetMapping("/list")
    public List<Organizations> listAll() {
        return organizationsService.list();
    }

    /**
     * 根据 ID 查询组织
     */
    @GetMapping("/{id}")
    public Organizations getById(@PathVariable Long id) {
        return organizationsService.getById(id);
    }

    /**
     * 新增组织
     */
    @PostMapping("/add")
    public String addOrganization(@RequestBody Organizations organization) {
        boolean saved = organizationsService.save(organization);
        return saved ? "新增成功" : "新增失败";
    }

    /**
     * 更新组织信息
     */
    @PutMapping("/update")
    public String updateOrganization(@RequestBody Organizations organization) {
        boolean updated = organizationsService.updateById(organization);
        return updated ? "更新成功" : "更新失败";
    }

    /**
     * 根据 ID 删除组织
     */
    @DeleteMapping("/delete/{id}")
    public String deleteOrganization(@PathVariable Long id) {
        boolean removed = organizationsService.removeById(id);
        return removed ? "删除成功" : "删除失败";
    }

    /**
     * 按服务区域和队伍人数筛选组织
     */
    @GetMapping("/search")
    public List<Organizations> searchOrganizations(
            @RequestParam(required = false) String address,
            @RequestParam(required = false) String personnelScale) {

        QueryWrapper<Organizations> queryWrapper = new QueryWrapper<>();

        // 按服务区域筛选
        if (address != null && !address.equals("全部")) {
            queryWrapper.eq("region", address);
        }

        // 按队伍人数筛选
        if (personnelScale != null && !personnelScale.equals("全部")) {
            switch (personnelScale) {
                case "1-20":
                    queryWrapper.between("personnel_scale", 1, 20);
                    break;
                case "21-50":
                    queryWrapper.between("personnel_scale", 21, 50);
                    break;
                case "51-100":
                    queryWrapper.between("personnel_scale", 51, 100);
                    break;
                case "100以上":
                    queryWrapper.gt("personnel_scale", 100);
                    break;
            }
        }

        return organizationsService.list(queryWrapper);
    }

    /**
     * 根据志愿者编号查询所属组织
     */
    @GetMapping("/searchByVolunteerId")
    public List<Organizations> searchByVolunteerId(@RequestParam Integer volunteerId) {
        // 查询志愿者信息
        Volunteer volunteer = volunteerService.getById(volunteerId);
        if (volunteer == null || volunteer.getOrganizationIds() == null || volunteer.getOrganizationIds().trim().isEmpty()) {
            return new ArrayList<>(); // 返回空列表
        }

        // 获取志愿者所属组织ID列表
        List<String> orgIdList = Arrays.asList(volunteer.getOrganizationIds().split(","));

        // 查询所有匹配的组织信息
        return organizationsService.list(new QueryWrapper<Organizations>().in("organization_id", orgIdList));
    }

    @GetMapping("/count")
    public int countVolunteers() {
        return Math.toIntExact(organizationsMapper.selectCount(null)); // 计算志愿者总数
    }
}
